<template>
    <div class="LoginBox">
        <div class="loginCentoxBox">
            <div class="loginCentox">
                <div class="centosleft">
                    <img src="../assets/title.png" />
                </div>
                <div class="centosright">
                    <Tabs :value="tabName" :animated="false" @on-click="changeTab">
                        <!--            -->
                        <TabPane label="" name="student" style="border-radius: 20px 0 0 0">
                            <div class="rightcontBox">
                                <h1>欢迎登录！</h1>
                                <Form ref="usernameLoginForm" :model="form" :rules="rules" class="loginFormBox">
                                    <FormItem prop="school">
                                        <Select placeholder="请选择所属学校" v-model="form.school" filterable prefix="my-prefix">
                                            <template #prefix>
                                                <img src="@/assets/school.png" style="width: 22px; height: 22px" />
                                            </template>
                                            <Option v-for="item in cityList" :value="item.code" :key="item.value">{{ item.name }}</Option>
                                        </Select>
                                    </FormItem>
                                    <FormItem prop="username">
                                        <Input v-model="form.username" size="large" clearable placeholder="请输入您的身份证号或手机号" autocomplete="off">
                                            <template #prefix>
                                                <img src="@/assets/username.png" style="width: 22px; height: 22px" />
                                            </template>
                                        </Input>
                                    </FormItem>
                                    <FormItem prop="password">
                                        <Input type="password" v-model="form.password" size="large" password placeholder="请输入密码" autocomplete="off">
                                            <template #prefix>
                                                <img src="@/assets/password.png" style="width: 22px; height: 22px" />
                                            </template>
                                        </Input>
                                    </FormItem>
                                    <FormItem prop="imgCode">
                                        <Row justify="space-between" class="code-row-bg" style="display: flex; align-items: center; overflow: hidden">
                                            <Input v-model="form.imgCode" size="large" clearable placeholder="请输入验证码" :maxlength="10" prefix="ios-lock" class="input-verify" style="width: 65%">
                                                <template #prefix>
                                                    <img src="@/assets/yzm.png" style="width: 22px; height: 22px" />
                                                </template>
                                            </Input>
                                            <div style="position: relative; width: 30%; margin-left: 5%">
                                                <Spin v-if="loadingCaptcha" fix></Spin>
                                                <img :src="captchaImg" @click="getCaptchaImg" alt="加载失败" style="width: 100%; cursor: pointer; display: block" />
                                            </div>
                                        </Row>
                                    </FormItem>
                                    <!--                 滑动验证码（不显示图片弃用）-->
                                    <!--                  <FormItem prop="code">-->
                                    <!--                    <slidingVerification ref="slidingVer" />-->
                                    <!--                  </FormItem>-->
                                    <FormItem>
                                        <Button :loading="loading" @click.native="submitLogin" long>登录</Button>
                                        <div class="last">
                                            <p @click="activationClick">激活账号</p>
                                            <p @click="goReset">忘记密码？</p>
                                        </div>
                                    </FormItem>
                                </Form>
                            </div>
                        </TabPane>
                    </Tabs>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {
    login,
    userInfo,
    githubLogin,
    qqLogin,
    weiboLogin,
    wechatLogin,
    dingdingLogin,
    workwechatLogin,
    getJWT,
    sendLoginSms,
    smsLogin,
    initCaptcha,
    drawCodeImage,
    getOtherSet,
    getNotice,
    loginJud,
    modifyPassFirstLogin,
    sendActivationCode,
    userInfoToken
} from '@/api/index';
import { validateMobile, validatePassword } from '@/libs/validate';
import Cookies from 'js-cookie';
import Header from '@/views/main-components/header';
import Footer from '@/views/main-components/footer';
import LangSwitch from '@/views/main-components/lang-switch';
import RectLoading from '@/views/my-components/xboot/rect-loading';
import CountDownButton from '@/views/my-components/xboot/count-down-button';
import util from '@/libs/util.js';
import slidingVerification from '@/views/my-components/xboot/sliding-verification.vue';
import SetPassword from '@/views/my-components/xboot/set-password.vue';
import CryptoJS from 'crypto-js';

export default {
    components: {
        SetPassword,
        slidingVerification,
        CountDownButton,
        RectLoading,
        LangSwitch,
        Header,
        Footer
    },
    data() {
        return {
            token: '',
            captchaId: '',
            captchaImg: '',
            loadingCaptcha: true,
            socialLogining: true,
            error: false,
            tabName: 'student',
            saveLogin: true,
            getSms: '获取验证码',
            loading: false,
            sending: false,
            errorCode: '',

            cityList: [],
            form: {
                school: '',
                username: '',
                password: '',
                mobile: '',
                imgCode: ''
            },
            rules: {
                school: [
                    {
                        required: true,
                        message: '学校不能为空',
                        trigger: 'blur'
                    }
                ],
                username: [
                    {
                        required: true,
                        message: '身份证号或手机号不能为空',
                        trigger: 'blur'
                    }
                ],
                password: [
                    {
                        required: true,
                        message: '密码不能为空',
                        trigger: 'blur'
                    }
                ],
                imgCode: [
                    {
                        required: true,
                        message: '验证码不能为空',
                        trigger: 'blur'
                    }
                ],
                mobile: [
                    {
                        required: true,
                        message: '手机号不能为空',
                        trigger: 'change'
                    },
                    {
                        validator: validateMobile,
                        trigger: 'change'
                    }
                ]
            },

            showModal: false,
            resource: '4' //
        };
    },
    methods: {
        // tab 切换
        changeTab(e) {
            this.tabName = e;
            if (e == 'student') {
                this.resource = '4';
            } else if (e == 'school') {
                this.resource = '2';
            } else {
                this.resource = '1';
            }
        },
        // 跳转到激活页面
        activationClick() {
            this.$router.push('/activation');
        },
        //跳转到忘记密码页面
        goReset() {
            this.$router.push('/reset');
        },
        // 验证码加载失败 ，重新点击
        getCaptchaImg() {
            this.loadingCaptcha = true;

            initCaptcha().then(res => {
                this.loadingCaptcha = false;
                if (res.success) {
                    this.captchaId = res.result;
                    this.captchaImg = drawCodeImage + this.captchaId;
                }
            });
        },

        afterLogin(res) {
            let accessToken = res.result;
            this.token = accessToken;
            //
            // getOtherSet().then((res) => {
            //   if (res.result) {
            //     let domain = res.result.ssoDomain;
            //     // Cookies.set("accessToken", accessToken, {
            //     //   domain: domain,
            //     //   expires: 7,
            //     // });
            //   }
            // });
            // 获取用户信息
            userInfoToken(accessToken).then(res => {
                this.resource = res.result.resource;
                console.log(this.resourc, "this.resource != '4'");
                // if (this.resource != '4') {
                //   this.$Message.error('登录入口错误！')
                // } else {
                if (res.success) {
                    // window.location.reload();
                    // 避免超过大小限制
                    this.setStore('accessToken', accessToken);
                    delete res.result.permissions;
                    let roles = [];
                    res.result.roles.forEach(e => {
                        roles.push(e.name);
                    });
                    delete res.result.roles;
                    this.setStore('roles', roles);
                    this.setStore('saveLogin', this.saveLogin);
                    if (this.saveLogin) {
                        // 保存7天
                        Cookies.set('userInfo', JSON.stringify(res.result), {
                            expires: 7
                        });
                        Cookies.set('currentUser', this.$route.name, {
                            expires: 7
                        });
                    } else {
                        Cookies.set('userInfo', JSON.stringify(res.result));
                        Cookies.set('currentUser', this.$route.name);
                    }

                    this.$store.commit('setRoute', this.$route.name);

                    this.setStore('userInfo', res.result);
                    this.$store.commit('setUserInfo', res.result);
                    // 加载菜单
                    util.initRouter(this);
                    console.log(this.saveLogin, 'bys');
                    // window.location.reload()
                    console.log();
                    this.$router.push({
                        name: 'home_index'
                    });
                }
                // }
            });
        },
        //登录提交
        submitLogin() {
            if (this.form.username == '' && this.form.password == '' && this.form.imgCode == '') {
                // this.$Message.error('输入有空！')
                this.$Message.error({
                    content: '输入有空！',
                    duration: 5,
                    closable: true
                });
            } else {
                this.$refs.usernameLoginForm.validate(valid => {
                    if (valid) {
                        this.loading = true;
                        // 将密钥转换为WordArray对象
                        const keyWordArray = CryptoJS.enc.Utf8.parse('d77f1e8084e21d96');
                        // 加密
                        const encrypted = CryptoJS.AES.encrypt(this.form.password, keyWordArray, {
                            mode: CryptoJS.mode.ECB,
                            padding: CryptoJS.pad.Pkcs7
                        });
                        login({
                            resource: '4',
                            username: this.form.username,
                            password: encrypted.toString(),
                            code: this.form.imgCode,
                            school: this.form.school,
                            saveLogin: this.saveLogin,
                            captchaId: this.captchaId
                        }).then(res => {
                            if (res.success) {
                                this.afterLogin(res);
                            } else {
                                this.loading = false;
                                this.getCaptchaImg();
                            }
                        });
                    }
                });
            }
        },

        relatedLogin() {
            let q = this.$route.query;
            let error = q.error;
            if (error !== '' && error !== undefined) {
                // this.$Message.error(error);
                this.$Message.error({
                    content: error,
                    duration: 5,
                    closable: true
                });
            }
            let related = q.related;
            let JWTKey = q.JWTKey;
            if (related && related == '1' && JWTKey) {
                getJWT({ JWTKey: JWTKey }).then(res => {
                    if (res.success) {
                        this.socialLogining = true;
                        let accessToken = res.result;
                        this.setStore('accessToken', accessToken);
                        getOtherSet().then(res => {
                            if (res.result) {
                                let domain = res.result.ssoDomain;
                                Cookies.set('accessToken', accessToken, {
                                    domain: domain,
                                    expires: 7
                                });
                            }
                        });
                        // 获取用户信息
                        userInfo().then(res => {
                            if (res.success) {
                                // 避免超过大小限制
                                delete res.result.permissions;
                                let roles = [];
                                res.result.roles.forEach(e => {
                                    roles.push(e.name);
                                });
                                delete res.result.roles;
                                this.setStore('roles', roles);
                                // 保存7天
                                Cookies.set('userInfo', JSON.stringify(res.result), {
                                    expires: 7
                                });
                                this.setStore('userInfo', res.result);
                                this.$store.commit('setUserInfo', res.result);
                                // 加载菜单
                                util.initRouter(this);
                                this.$router.push({
                                    name: 'home_index'
                                });
                            } else {
                                this.socialLogining = false;
                                // this.$Message.error("获取登录用户信息失败");
                                this.$Message.error({
                                    content: '获取登录用户信息失败',
                                    duration: 5,
                                    closable: true
                                });
                            }
                        });
                    } else {
                        this.socialLogining = false;
                        // this.$Message.error("使用第三方账号登录失败");
                        this.$Message.error({
                            content: '使用第三方账号登录失败',
                            duration: 5,
                            closable: true
                        });
                    }
                });
            } else {
                this.socialLogining = false;
            }
        },
        getCityList() {
            this.loading = true;
            this.postRequest('/schoolCode/getAll').then(res => {
                if (res.success) {
                    this.loading = false;
                    this.cityList = res.result;
                }
            });
        },

        showNotice() {
            getNotice().then(res => {
                if (res.success) {
                    if (!res.result) {
                        return;
                    }
                    let data = res.result;
                    if (data.open && (data.title || data.content) && data.position == 'LOGIN') {
                        this.$Notice.info({
                            title: data.title,
                            desc: data.content,
                            duration: data.duration
                        });
                    }
                }
            });
        },
        test() {
            this.$Notice.info({
                title: '测试体验账号',
                desc: '账号：test或test2<br>密码：123456'
            });
        }
        //   信息补充提交
    },
    mounted() {
        this.showNotice();
        // this.relatedLogin();
        this.getCaptchaImg();
        this.getCityList();
        // this.form.code = false
    }
};
</script>

<style lang="less">
@import './login.less';
</style>
